//
//  ModifyPhoneNumberController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/31.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class ModifyPhoneNumberController: UIViewController {
    
    var baseView = UIView()
    fileprivate var securityButton :UIButton!
    /// 手机号
    var phoneTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入原本手机号码"
        textField.backgroundColor = UIColor.white
        textField.autocorrectionType = UITextAutocorrectionType.no
        textField.autocapitalizationType = .none
        textField.keyboardType = .numberPad
        
        
        let imageView = UIImageView(image: UIImage.init(named: "Icon_手机")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 38, height: 24)
        imageView.contentMode = .scaleAspectFit
        
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
        
    }()
   fileprivate lazy var unavailableButton: UIButton = {
        let button = UIButton()
        button.setTitle("手机不可用？", for: .normal)
        button.setTitleColor(colorWith255RGB(16, g: 142, b: 233), for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        button.addTarget(self, action: #selector(doUnavailableButtonAction), for: .touchUpInside)
        return button
    }()
    
    var securityTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入短信验证码"
        textField.keyboardType = .numberPad
        textField.backgroundColor = UIColor.white
        
        let imageView = UIImageView(image: UIImage.init(named: "reply_n")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 38, height: 24)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    /// 密码
    var passwordTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入密码"
        textField.isSecureTextEntry = true
        textField.backgroundColor = UIColor.white
        
        
        let imageView = UIImageView(image: UIImage.init(named: "ic_lock")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 38, height: 24)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var commitButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_blue
        button.layer.cornerRadius = 6
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        
        return button
    }()
    @objc func doUnavailableButtonAction() {
  self.navigationController?.pushViewController(AppealPhoneNoController(), animated: true)
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        WWEndLoading()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.title = "验证旧手机"
        
        self.setupviews()
        self.setupViewOldView()
    }
    
    func setupviews() {
        let warningLabel = UILabel()
        warningLabel.backgroundColor = UIColor.white
        warningLabel.text = "   更换手机后，下次登录可使用新手机登录"
        warningLabel.font = wwFont_Regular(15)
        warningLabel.textColor = colorWith255RGB(102, g: 102, b: 102)
        self.view.addSubview(warningLabel)
        warningLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(40)
        }
        
        self.view.addSubview(baseView)
        self.baseView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(warningLabel.snp.bottom).offset(5)
        }
    }

    var isNewView = false
    
    //『输入变量』。用户信息
    var userInfoModel: UserInfoModel?
    
    //验证原手机视图
    func setupViewOldView() {
        self.view.addSubview(baseView)
        self.baseView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
        }
        self.isNewView = false
        
        for view in self.baseView.subviews {
            view.removeFromSuperview()
        }
        
        if self.userInfoModel != nil {
            self.phoneTextField.text = self.userInfoModel?.cellPoneNumber
            self.phoneTextField.isEnabled = false
        }
        else {
            self.phoneTextField.text = ""
            self.phoneTextField.isEnabled = true
        }
        
        self.baseView.addSubview(self.phoneTextField)
        self.phoneTextField.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(self.baseView)
            make.height.equalTo(50)
        }
        
        let separatorLine = UIView()
        separatorLine.backgroundColor = UIColor.clear
        self.baseView.addSubview(separatorLine)
        separatorLine.snp.makeConstraints { (make) in
            make.top.equalTo(self.phoneTextField.snp.bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(1)
        }
        
        let securityView = UIView()
        securityView.backgroundColor = UIColor.white
        self.baseView.addSubview(securityView)
        securityView.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(self.phoneTextField)
            make.top.equalTo(separatorLine.snp.bottom)
        }
        
        self.baseView.addSubview(self.securityTextField)
        self.securityTextField.snp.makeConstraints { (make) in
            make.left.bottom.top.equalTo(securityView)
        }
        
        let button = UIButton()
        button.addTarget(self, action: #selector(doCountDownAction(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 10
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button.setTitle("获取验证码", for: .normal)
        button.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        securityView.addSubview(button)
        button.snp.makeConstraints { (make) in
            make.left.equalTo(self.securityTextField.snp.right)
            make.centerY.equalTo(self.securityTextField)
            make.right.equalTo(securityView).offset(-15)
            make.size.equalTo(CGSize.init(width: 80, height: 30))
        }
        self.baseView.addSubview(self.unavailableButton)
        self.unavailableButton.snp.makeConstraints { (make) in
            make.right.equalTo(securityView).offset(-10)
            make.top.equalTo(securityView.snp.bottom).offset(10)
            make.width.equalTo(100)
            make.height.equalTo(30)
        }
        
        
        self.commitButton.addTarget(self, action: #selector(doOldCommitAction), for: .touchUpInside)
        self.commitButton.setTitle("下一步", for: .normal)
        self.baseView.addSubview(self.commitButton)
        self.commitButton.snp.makeConstraints { (make) in
            make.top.equalTo(securityView.snp.bottom).offset(60)
            make.width.equalTo(169)
            make.height.equalTo(45)
            make.centerX.equalTo(self.baseView)
        }
    }
    
    //验证新手机界面
    func setupNewViews() {
        self.baseView.snp.removeConstraints()
        self.baseView.removeFromSuperview()
        let warningLabel = UILabel()
        warningLabel.backgroundColor = UIColor.white
        warningLabel.text = "   更换手机后，下次登录可使用新手机登录"
        warningLabel.font = wwFont_Regular(15)
        warningLabel.textColor = colorWith255RGB(102, g: 102, b: 102)
        self.view.addSubview(warningLabel)
        warningLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(40)
        }
        
        self.view.addSubview(baseView)
        self.baseView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(warningLabel.snp.bottom).offset(5)
        }
        self.isNewView = true
        self.navigationItem.title = "修改手机号"
        
        self.phoneTextField.text = ""
        self.phoneTextField.isEnabled = true
        self.phoneTextField.placeholder = "请输入新的手机号码"
        self.phoneTextField .addTarget(self, action: #selector(textFieldChangeClick(_textField:)), for: .editingChanged)
        self.securityTextField.text = ""
        
        self.baseView.addSubview(self.phoneTextField)
        self.phoneTextField.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(self.baseView)
            make.height.equalTo(50)
        }
        
        let separatorLine = UIView()
        separatorLine.backgroundColor = UIColor.clear
        self.baseView.addSubview(separatorLine)
        separatorLine.snp.makeConstraints { (make) in
            make.top.equalTo(self.phoneTextField.snp.bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(1)
        }
        
        
        let securityView = UIView()
        securityView.backgroundColor = UIColor.white
        self.baseView.addSubview(securityView)
        securityView.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(self.phoneTextField)
            make.top.equalTo(separatorLine.snp.bottom)
        }
        

        self.baseView.addSubview(self.securityTextField)
        self.securityTextField.snp.makeConstraints { (make) in
            make.left.bottom.top.equalTo(securityView)
        }
        
        
        self.securityButton = UIButton()
        self.securityButton.addTarget(self, action: #selector(doCountDownAction(_:)), for: .touchUpInside)
        self.securityButton.layer.cornerRadius = 10
        self.securityButton.isUserInteractionEnabled = false
        self.securityButton.alpha = 0.4
        self.securityButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        self.securityButton.setTitle("获取验证码", for: .normal)
        self.securityButton.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        securityView.addSubview(self.securityButton)
        self.securityButton.snp.makeConstraints { (make) in
            make.left.equalTo(self.securityTextField.snp.right)
            make.centerY.equalTo(self.securityTextField)
            make.right.equalTo(securityView).offset(-15)
            make.size.equalTo(CGSize.init(width: 80, height: 30))
        }
        
        
        self.commitButton.removeTarget(self, action: #selector(doOldCommitAction), for: .touchUpInside)
        self.commitButton.addTarget(self, action: #selector(doNewCommitAction), for: .touchUpInside)
        self.commitButton.setTitle("提交", for: .normal)
        self.baseView.addSubview(self.commitButton)
        self.commitButton.snp.makeConstraints { (make) in
            make.width.equalTo(170)
            make.height.equalTo(45)
            make.centerX.equalTo(self.baseView)
            make.top.equalTo(securityView.snp.bottom).offset(60)
        }
    }
    @objc func textFieldChangeClick(_textField : UITextField){
        
        
        let phoneNumber = self.phoneTextField.text
        
        if Tool.isValidatePhoneNum(phoneNumber!) {
            securityButton.isUserInteractionEnabled = true
            securityButton.alpha = 1;
        }else{
            securityButton.isUserInteractionEnabled = false
            securityButton.alpha = 0.4;
        }
    }
    @objc func doCountDownAction(_ button: UIButton) {
         let phoneNumber = self.phoneTextField.text
        self.checkPhoneNumber(phoneNumber!,isNewPhone: self.isNewView, completion: { (response) in
            if !response.success {
                
                WWError(response.message)
            }
            else {
                button.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: button.backgroundColor!, countColor: UIColor.gray)
                
                UserModel.requestSecurityCode(phoneNumber: phoneNumber!, flag: FlagType.agentapply) { (response) in
                    if response.success {
                        
                        #if DEBUG
                            WWInform(response.value ?? "好像是空的")
                        #else
                        #endif
                    }
                    else {
                        WWInform("发送失败")
                    }
                }

            }
        })
    }
    @objc func doOldCommitAction() {
        guard let phoneNumber = self.phoneTextField.text, phoneNumber.characters.count > 0 else {
            WWError("请输入手机号码后再获取")
            return
        }
        guard Tool.isValidatePhoneNum(phoneNumber) else {
            WWError("请输入正确的11位手机号码")
            return
        }
        guard let verificationCode = self.securityTextField.text, verificationCode.characters.count > 0 else {
            WWError("请输入验证码")
            return
        }
        
        WWBeginLoadingWithStatus("校验验证码")
        UserModel.checkVerification(phoneNumber, verificaitonCode: verificationCode, flag: .agentapply) { (response) in
            if response.success {
                
                WWBeginLoadingWithStatus("校验手机号")
                CommonModel.checkPhoneNumber(phoneNumber){(response) in
                    if response.success {
                        
                        self.setupNewViews()
                        WWSuccess("校验通过，你输入新手机号")
                    }
                    else
                    {
                        WWError(response.message)
                    }
                    
                }

            }
            else {
                WWError(response.message)
            }
        }
    }
    
    @objc func doNewCommitAction() {
        guard let phoneNumber = self.phoneTextField.text, phoneNumber.count > 0 else {
            WWError("请输入手机号码后再获取")
            return
        }
        guard Tool.isValidatePhoneNum(phoneNumber) else {
            WWError("请输入正确的11位手机号码")
            return
        }
        guard let verificationCode = self.securityTextField.text, verificationCode.count > 0 else {
            WWError("验证码不能为空")
            return
        }
        
        WWBeginLoadingWithStatus("校验验证码")
        UserModel.checkVerification(phoneNumber, verificaitonCode: verificationCode, flag: .agentapply) { (response) in
            if response.success {
                
                WWBeginLoadingWithStatus("校验手机号")
                CommonModel.checkPhoneNumber(phoneNumber,isNewPhone: true){(response) in
                    if response.success {
                        
                        WWBeginLoadingWithStatus("开始修改..")
                        CommonModel.modifyPhoneNumber(phoneNumber) { (response) in
                            if response.success {
                                WWSuccess("修改成功")
                                NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: kNotificationUserInfoChanged), object: nil, userInfo: nil)
                                self.navigationController?.popViewController(animated: true)
                            }
                            else {
                                WWError(response.message)
                            }
                        }
                        
                    }
                    else
                    {
                        WWError(response.message)
                    }
                    
                }
                
            }
            else {
                WWError(response.message)
            }
        }
        
        
    }
    
    
    /// 校验手机号
    private func checkPhoneNumber(_ phoneNumber: String,isNewPhone:Bool , completion: @escaping (WWResponse) -> Void) {
        CommonModel.checkPhoneNumber(phoneNumber,isNewPhone: isNewPhone){(response) in
            completion(response)
        }
    }
}
